package cn.wolfcode.util;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * public static HttpSession getSession() {
 * ServletRequestAttributes attrs =
 * (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
 * return attrs.getRequest().getSession();
 * }
 */
public class UserContext {
    //抽取常量session中使用的key值
    public static final String USER_IN_SESSION = "USER_IN_SESSION";
    public static final String PERMISSION_IN_SESSION = "PERMISSION_IN_SESSION";

    //获取session对象:springmvc提供的，在任意地方都可以获取
    public static HttpSession getSession() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attrs.getRequest().getSession();
    }

    //springvmc提供的工具类来获取我们的session对象

    public static void setCurrentUser(Employee employee) {
        getSession().setAttribute(UserContext.USER_IN_SESSION,employee);
    }

    public static Employee getCurrentUser() {
        Employee employee = (Employee)getSession().getAttribute(UserContext.USER_IN_SESSION);
        return employee;
    }

    //权限相关的session
    public static void setPermission(List<String> list) {
        getSession().setAttribute(UserContext.PERMISSION_IN_SESSION,list);
    }

    //获得权限相关的session
    public static List<String> getPermission() {
            List<String> permissions = (List<String>) getSession().getAttribute(UserContext.PERMISSION_IN_SESSION);
            return permissions;
    }
}
